/************************************************************************
*************************************************************************
*************************************************************************

binplot.ado

Splits the domain of a variable into equal-sized bins and plots the average.

20151207:	(@) Created


*************************************************************************
*************************************************************************
************************************************************************/


cap program drop binplot
program binplot
	syntax varlist [if] [fweight pweight aweight iweight] , Xvar(varname) [bw(real 0) OPTscatter(string) lineone linebreak median stat(string) ]
	
	quietly {
		preserve
		
		marksample useme
		
		keep if `useme'
		
		if `bw' == 0 {
			sum `xvar'
			local bw = ( r(max) - r(mean) ) / 10
		}
		
		gen bin = `xvar' - mod(`xvar', `bw')
		
		
		if "`stat'" == "" {
			local stat mean
		}
		
		
		collapse (`stat') `varlist' [`weight'`exp'], by(bin)
		
		gen `xvar' = bin + `bw'/2
		
		if "`lineone'" == "" {
			local command twoway
			foreach var of varlist `varlist' {
				local command `command' (scatter `var' `xvar')
			}
			
			di `"`command', graphregion(color(white)) `optscatter'"'
			`command', graphregion(color(white)) `optscatter'
		}
		else if "`linebreak'" == "" {
			local command twoway
			foreach var of varlist `varlist' {
				local command `command' (scatter `var' `xvar') (lfit `var' `xvar')
			}
			`command', graphregion(color(white)) `optscatter'
		}
		else {
			local command twoway
			foreach var of varlist `varlist' {
				local command `command' (scatter `var' `xvar') (lfit `var' `xvar' if `xvar' < 0) (lfit `var' `xvar' if `xvar' > 0)
			}
			`command', graphregion(color(white)) `optscatter'
		}
		
		restore
	}


end
